import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/device/lock/api.dart";
import "package:ct_pa_majordomo/utils/date_tools.dart";
import "package:ct_pa_majordomo/widgets/divider/solid_divider.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";

class OpeRecord extends StatefulWidget {
  final Map info;
  const OpeRecord({super.key, required this.info});

  @override
  State<StatefulWidget> createState() => _OpeRecordState();

}

class _OpeRecordState extends State<OpeRecord> {
  List _list = [];
  bool _isLoading = false;
  bool _hasMore = true;
  late ScrollController _scrollController;
  Map<String, dynamic> _filtter = {
    "pageNum": 1,
    "pageSize": 10,
    "lockId": null,
    "recordType": 4, // 密码开锁记录recordType为4
    "searchStr": ""
  };
  
  Future<void> _getRecords({bool isRefresh = false}) async {
    if (_isLoading) return;
    
    setState(() {
      _isLoading = true;
    });

    try {
      if (isRefresh) {
        // 下拉刷新时重置页码
        _filtter["pageNum"] = 1;
      }

      Map resData = await lockApi.getUnlockRecords(int.parse(widget.info["lock"]["lockId"]), _filtter);
      
      List newData = resData["rows"] ?? [];
      setState(() {
        if (isRefresh || _filtter["pageNum"] == 1) {
          // 刷新或第一页时直接替换数据
          _list = newData;
        } else {
          // 加载更多时追加数据
          _list = [..._list, ...newData];
        }
        
        // 判断是否还有更多数据
        _hasMore = newData.length >= _filtter["pageSize"];
        
        // 更新页码
        if (_hasMore && !isRefresh) {
          _filtter["pageNum"] = (_filtter["pageNum"] as int) + 1;
        }
      });
    } catch (error) {
      print(error);
      EasyLoading.showToast("加载失败，请重试");
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  // 刷新数据
  Future<void> _onRefresh() async {
    await _getRecords(isRefresh: true);
  }

  // 加载更多数据
  void _loadMore() {
    if (_hasMore && !_isLoading) {
      _getRecords();
    }
  }

  @override
  void initState() {
    super.initState();
    print("userId:>>>>>>>${widget.info}");
    setState(() {
      _filtter["searchStr"] = widget.info["keyboardPwd"];
      _filtter["lockId"] = widget.info["lock"]["lockId"];
    });

    // 初始化ScrollController并添加滚动监听
    _scrollController = ScrollController();
    _scrollController.addListener(() {
      // 判断是否滚动到底部
      if (_scrollController.position.pixels >= _scrollController.position.maxScrollExtent - 50) {
        _loadMore();
      }
    });

    _getRecords();
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        iconTheme: const IconThemeData(color: Colors.white),
        title: const Text("操作记录", style: TextStyle(color: Colors.white),),
        centerTitle: true,
        backgroundColor: ThemeVars.colorPrimaryDark,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios_new),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
      ),
      body: Container(
        decoration: const BoxDecoration(
          color: Colors.white,
        ),
        child: RefreshIndicator(
          onRefresh: _onRefresh,
          child: _list.isEmpty && !_isLoading 
            ? _buildEmptyView()
            : _buildRecordList(),
        ),
      )
    );
  }

  // 构建空视图
  Widget _buildEmptyView() {
    return ListView(
      physics: const AlwaysScrollableScrollPhysics(),
      children: const [
        SizedBox(height: 100),
        Center(
          child: Text("暂无操作记录", style: TextStyle(color: ThemeVars.colorTextSec, fontSize: 16)),
        ),
      ],
    );
  }

  // 构建记录列表
  Widget _buildRecordList() {
    return ListView.builder(
      controller: _scrollController,
      physics: const AlwaysScrollableScrollPhysics(),
      itemCount: _list.length + 1, // 加1是为了显示底部加载更多
      itemBuilder: (context, index) {
        if (index == _list.length) {
          // 构建底部加载状态视图
          return _buildLoadMoreView();
        } else {
          // 构建记录项
          return _buildRecordItem(_list[index]);
        }
      },
    );
  }

  // 构建单个记录项
  Widget _buildRecordItem(Map record) {
    String timeStr = DateTools.formatYMD(record["lockDate"], format: "{y}-{m}-{d} {h}:{i}") ?? "未知时间";
    String actionStr = "开锁";
    
    return Column(
      children: [
        Padding(
          padding: const EdgeInsets.fromLTRB(15, 16, 10, 16),
          child: Row(
            children: [
              const Icon(Icons.access_time, color: ThemeVars.colorPrimary, size: 24),
              const SizedBox(width: 8),
              Expanded(
                child: Text("$timeStr $actionStr", 
                  style: const TextStyle(color: ThemeVars.colorTextTer, fontSize: 16),
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            ],
          ),
        ),
        const SolidDivider(padding: EdgeInsets.only(left: 15)),
      ],
    );
  }

  // 构建底部加载更多视图
  Widget _buildLoadMoreView() {
    if (_isLoading) {
      return const Padding(
        padding: EdgeInsets.symmetric(vertical: 16),
        child: Center(
          child: CupertinoActivityIndicator(),
        ),
      );
    } else if (!_hasMore) {
      return const Padding(
        padding: EdgeInsets.symmetric(vertical: 16),
        child: Center(
          child: Text("- 没有更多了 -", style: TextStyle(color: ThemeVars.colorTextSec, fontSize: 14)),
        ),
      );
    } else {
      return const SizedBox(height: 16);
    }
  }
}